/* On{X} Script: Sound alarm on full volume on receiving specific SMS (uses SetOn{x})
 *
 * Developer: Gaurav Nandwani
 *
 * Description:
 *
 * This rule monitors for incoming SMS from particular number(s) and checks for defined text 
 * (case-insensitive). On receiving desired SMS the script increases the device music volume to 100% 
 * (using SetOn{x}, as this is not directly available from On{X} API as of now). Then it plays the 
 * defined alarm (audio) file using the default audio player.
 * 
 * Usage:
 * 
 * Change following variables as needed:
 * 
 * phoneNumbers	- Array of phone numbers which can trigger the alarm.
 *                 * Note: I used array insted of a single number as I was getting input number 
 *                   different format from different SMS applications. E.g. I was getting my number 
 *                   with country code starting with '+' or sometimes without country code & 
 *                   starting with '0'.
 *                   So keeping this in mind, you'd want to put the trigger phone number in all 
 *                   possible formats you expect or change the phone number condition such that it 
 *                   matches the phone number(s) you desire.
 * messageText   - Message text which will trigger the alarm if coming from 'phoneNumbers'
 * alarmFilePath - Audio file which should be played when alarm is triggered. The file path should 
 *                 be in URL format. If local path (SDCard or Phone Memory) then it should start 
 *                 with 'file://', as in example value)
 */

// Initializing variables 

var phoneNumbers = ['+1234567890', '0234567890', '234567890'];
var messageText = 'find my phone';
var alarmFilePath = 'file:///sdcard/Ringtones/LoudRing.mp3';

// End of variables initializing 

console.log('Started script: When ' + phoneNumbers[0] + ' texts me "' +  messageText + '" sound alarm on full volume.');

//  Register callback on sms received event
device.messaging.on('smsReceived', function (sms) {
    var phoneIndex = phoneNumbers.indexOf(sms.data.from);
    if (phoneIndex > -1 && sms.data.body.toLowerCase() === messageText.toLowerCase()) {
        // Increase music volume
        device.applications.launch('setonx', {message:'audio', stream:'music', volume:'100'}, null);        
        // Play Alarm Sound
        device.applications.launchViewer(alarmFilePath, 'audio/*');
        console.info('Played alarm in response to "' + messageText+ '" SMS from "' + phoneNumbers[phoneIndex] + '".');
    }
});

console.log('Completed script: When ' + phoneNumbers[0] + ' texts me "' +  messageText + '" sound alarm on full volume.');
